<?php


namespace App\HttpController\Base;


use EasySwoole\Http\AbstractInterface\Controller;

class Base extends Controller
{
    public function index()
    {
        $this->actionNotFound('index');
        // $this->error('方法不存在');
    }

    public function getRawData()
    {
        $data = $this->request()->getSwooleRequest()->getContent();
        if ($data) {
            return json_decode($data, true);
        }
        return [];
    }

    public function actionNotFound(?string $action)
    {
        $this->error("方法 {$action} 不存在");
    }

    protected function success($msg = 'OK', $data = [], $code = 1)
    {
        $this->apiReturn($code, $data, $msg);
    }

    protected function error($msg = 'OK', $code = 0)
    {
        $this->apiReturn($code, [], $msg);
    }


    protected function apiReturn($code, $result, $msg)
    {
        if (!$this->response()->isEndResponse()) {
            $data = [
                "code" => $code,
                "result" => $result,
                "msg" => $msg
            ];
            $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
            $this->response()->withStatus(200);
            return true;
        } else {
            return false;
        }
    }
}